package mysql

import (
	"fmt"
	"gitee.com/dreamwood/ez"
	"os/exec"
)

func GenerateConfig(c *Creator) {
	c.SrcDirs = make(map[string]bool)
	for _, field := range c.Fields {
		field.CreateConfig()
		if field.GetSrcDir() != "" {
			c.SrcDirs[field.GetSrcDir()] = true
		}
	}
	CreateOrmConfigFile(c)
}
func createModelFile(c *Creator, content []byte) {
	path := fmt.Sprintf(
		"%s/app/%s/models/%s_.go",
		root, c.Table.Path, c.Table.Name)
	ez.CreateFile(path, content)
	wg.Add(1)
	go func() {
		e := exec.Command("go", "fmt", path).Run()
		if e != nil {
			ez.Debug("fmt Model文件时出错")
		}
		wg.Done()
	}()
	ez.PrintSuccess(fmt.Sprintf("%s Model文件创建完成", c.Table.Name))
}
func createEzModelConfigFile(c *Creator, content []byte) {
	path := fmt.Sprintf(
		"%s/app/%s/auto/v1/mc/%s_Config.go",
		root, c.Table.Path, c.Table.Name)
	ez.CreateFile(path, content)
	wg.Add(1)
	go func() {
		e := exec.Command("go", "fmt", path).Run()
		if e != nil {
			println("go fmt 5", e.Error())
		}
		wg.Done()
	}()
	ez.PrintSuccess(fmt.Sprintf("%s EzModelConfig文件创建完成", c.Table.Name))
}
func createCrudFile(c *Creator, content []byte) {
	path := fmt.Sprintf(
		"%s/app/%s/models/%s_CURD.go",
		root, c.Table.Path, c.Table.Name)
	ez.CreateFile(path, content)
	go func() {
		e := exec.Command("go", "fmt", path).Run()
		if e != nil {
			println("go fmt 5", e.Error())
		}
	}()
	ez.PrintSuccess(fmt.Sprintf("%s CRUD文件创建完成", c.Table.Name))
}

/***************************Model创建*********************************/
type OrmField struct {
	Name string
	Type string
	Tags string
}

func CreateModel(creator *Creator) {
	data := twigger.Render("/mysql/model.twig", creator)
	createModelFile(creator, []byte(data))
}
func CreateEzModelConfig(creator *Creator) {
	data := twigger.Render("/mysql/ez_model_config.twig", creator)
	createEzModelConfigFile(creator, []byte(data))
}

func CreateCrud(creator *Creator) {
	data := twigger.Render("/mysql/model_func.twig", creator)
	createCrudFile(creator, []byte(data))
}

func CreateMod(creator *Creator) {
	data := twigger.Render("/mysql/model_mod.twig", creator)
	path := fmt.Sprintf(
		"%s/app/%s/models/%s_Mod.go",
		root, creator.Table.Path, creator.Table.Name)
	if !ez.FileExist(path) {
		ez.CreateFile(path, []byte(data))
		wg.Add(1)
		go func() {
			e := exec.Command("go", "fmt", path).Run()
			if e != nil {
				println("go fmt 5", e.Error())
			}
			wg.Done()
		}()
		ez.PrintSuccess(fmt.Sprintf("%s Model_MOD文件创建完成", creator.Table.Name))
	} else {
		ez.PrintWarning(fmt.Sprintf("%s Model_MOD文件已存在，跳过", creator.Table.Name))
	}
}

func CreateMigrate(creator *Creator) {
	//单表migrate
	dataS := twigger.Render("/mysql/model_migrate_one.twig", creator)
	pathS := fmt.Sprintf(
		"%s/app/%s/auto/v1/migrate/run_one/%s/Migrate.go",
		root, creator.Table.Path, creator.Table.Name)
	ez.CreateFile(pathS, []byte(dataS))
	wg.Add(1)
	go func() {
		e := exec.Command("go", "fmt", pathS).Run()
		if e != nil {
			println("go fmt CreateMigrate", e.Error())
		}
		wg.Done()
	}()
	ez.PrintSuccess(fmt.Sprintf("%s 独立Migrate文件创建完成", creator.Table.Name))

	//统一migrate
	data := twigger.Render("/mysql/model_migrate.twig", creator)
	path := fmt.Sprintf(
		"%s/app/%s/auto/v1/migrate/%s_Migrate.go",
		root, creator.Table.Path, creator.Table.Name)
	ez.CreateFile(path, []byte(data))
	wg.Add(1)
	go func() {
		e := exec.Command("go", "fmt", path).Run()
		if e != nil {
			println("go fmt CreateMigrate", e.Error())
		}
		wg.Done()
	}()
	ez.PrintSuccess(fmt.Sprintf("%s 统一Migrate文件创建完成", creator.Table.Name))

	//覆盖一个全部写入的程序
	content := `package main

import _ "api/app/` + creator.Table.Path + `/auto/v1/migrate"

func main() {
	//什么也不做，只是加载

}
`
	path = fmt.Sprintf(
		"%s/app/%s/auto/v1/migrate/run_all/migrate_all.go",
		root, creator.Table.Path)
	ez.CreateFile(path, []byte(content))
	wg.Add(1)
	go func() {
		e := exec.Command("go", "fmt", path).Run()
		if e != nil {
			println("go fmt CreateMigrate", e.Error())
		}
		wg.Done()
	}()
	//独立的配置文件
	config := `package config

import (
	"api/public/global"
	"fmt"
	"gitee.com/dreamwood/ez"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

var db *gorm.DB

func MigrateDb() *gorm.DB {
	if db == nil {
		initDb()
	}
	return db
}
func initDb() {
	dsn := "root:root@tcp(127.0.0.1:3306)/ez_v1?charset=utf8&loc=Local&parseTime=true"
	gormDB, err := gorm.Open(mysql.New(mysql.Config{
		DSN:                       dsn,
		DefaultStringSize:         256,   // string 类型字段的默认长度
		DisableDatetimePrecision:  false, // 禁用 datetime 精度，MySQL 5.6 之前的数据库不支持
		DontSupportRenameIndex:    true,  // 重命名索引时采用删除并新建的方式，MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
		DontSupportRenameColumn:   true,  // 用 change 重命名列，MySQL 8 之前的数据库和 MariaDB 不支持重命名列
		SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
	}), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		ez.Debug(fmt.Sprintf("gorm数据库初始化失败:%s", err.Error()))
		return
	}
	db = gormDB
	global.DB = gormDB
	ez.Debug("MYSQL 初始化完成")
}

`
	path = fmt.Sprintf(
		"%s/app/%s/auto/v1/migrate/config/db.go",
		root, creator.Table.Path)
	if !ez.FileExist(path) {
		ez.CreateFile(path, []byte(config))
		wg.Add(1)
		go func() {
			e := exec.Command("go", "fmt", path).Run()
			if e != nil {
				println("go fmt CreateApiPageReg", e.Error())
			}
			wg.Done()
		}()
	} else {
		ez.PrintWarning(fmt.Sprintf("%s 数据Migration配置文件已存在，跳过", creator.Table.Name))
	}
	//ez.CreateFile(path, []byte(config))
	//wg.Add(1)
	//go func() {
	//	e := exec.Command("go", "fmt", path).Run()
	//	if e != nil {
	//		println("go fmt CreateMigrate db.go", e.Error())
	//	}
	//	wg.Done()
	//}()
}

func CreateApiPageReg(creator *Creator) {
	data := twigger.Render("/mysql/reg_pages.twig", creator)
	path := fmt.Sprintf(
		"%s/app/%s/auto/v1/reg/pages.go",
		root, creator.Table.Path)

	ez.PrintSuccess(fmt.Sprintf("%s 页面和接口注册文件创建完成", creator.Table.Name))
	if !ez.FileExist(path) {
		ez.CreateFile(path, []byte(data))
		wg.Add(1)
		go func() {
			e := exec.Command("go", "fmt", path).Run()
			if e != nil {
				println("go fmt CreateApiPageReg", e.Error())
			}
			wg.Done()
		}()
	} else {
		ez.PrintWarning(fmt.Sprintf("%s 页面和接口注册文件已存在，跳过", creator.Table.Name))
	}

}
